﻿using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Service.Model
{
    public class CertResult
    {
        /// <summary>
        /// 是否申请成功
        /// </summary>
        public bool Successed { get; set; }
        /// <summary>
        /// 错误的情况下，错误信息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 通配符域名忽略*
        /// </summary>
        public string DomainName { get; set; }

        public string FileName
        {
            get
            {
                if (!string.IsNullOrEmpty(DomainName))
                {
                    return DomainName.Replace("*", "").TrimStart('.').TrimEnd('.').Trim();
                }
                return string.Empty;
            }
        }
        /// <summary>
        /// 被CA认证过的公钥
        /// </summary>
        public byte[] CertedCrt { get; set; }
        /// <summary>
        /// 私钥
        /// </summary>
        public RSA PrivateRsa { get; set; }
        /*
         * 证书
         * **/
        /// <summary>
        /// PEM
        /// </summary>
        public string Pem 
        {
            get
            {
                if (CertedCrt != null&& CertedCrt.Length>0)
                {
                    X509Certificate2 cert = new X509Certificate2(CertedCrt);
                    X509Chain chain = new X509Chain();
                    chain.Build(cert);
                    StringBuilder sb=new StringBuilder();
                    for (int i = 0; i < chain.ChainElements.Count - 1; i++)
                    {
                        if (chain.ChainElements[i].Certificate != cert)
                        {
                            byte[] certData = chain.ChainElements[i].Certificate.Export(X509ContentType.Cert);
                            var content = Convert.ToBase64String(certData,Base64FormattingOptions.None);
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int j = 0; j < content.Length; j += 64)
                            {
                                stringBuilder.Append($"{content.Substring(j, Math.Min(64, content.Length - j))}\n");
                            }
                            string pem = $"-----BEGIN CERTIFICATE-----\n{stringBuilder}-----END CERTIFICATE-----\n";
                            sb.Append(pem);
                        }
                    }
                    return sb.ToString();
                }
                return string.Empty;
            }
        }
        /// <summary>
        /// 私钥
        /// </summary>
        public string Key 
        {
            get
            {
                if (PrivateRsa != null)
                {
                    return PrivateRsa.ExportPkcs8PrivateKeyPem();
                }
                return string.Empty;
            }
        }

        public string PfxPassword { get; private set; }
        /// <summary>
        /// IIS中使用的证书
        /// </summary>
        public byte[] Pfx 
        {
            get
            {
                if (PrivateRsa != null && CertedCrt != null&& CertedCrt.Length>0)
                {
                    RSA rsaPrivateKey = PrivateRsa;
                    RSA privateKey = RSA.Create();
                    X509Certificate2 certificate = new X509Certificate2(CertedCrt);
                    certificate = certificate.CopyWithPrivateKey(rsaPrivateKey);
                    var password = GenerateRandomPassword(5);
                    byte[] pfxData = certificate.Export(X509ContentType.Pfx, password.ToString());
                    PfxPassword = password.ToString();
                    return pfxData;
                }
                return null;
            }
        }

        private string GenerateRandomPassword(int length)
        {
            const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";  // 定义可用的字符集
            Random random = new Random();  // 创建一个Random实例
            char[] passwordArray = new char[length];  // 存放生成密码的字符数组

            for (int i = 0; i < length; i++)
            {
                passwordArray[i] = chars[random.Next(chars.Length)];  // 从字符集中随机选一个字符
            }

            return new string(passwordArray);  // 将字符数组转为字符串并返回
        }
    }
}
